package org.example.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author lyz 处理特殊请求
 * @Date 2025/3/27 14:28
 */
public class RequestUtils {

    public static String sendRequest(String url, Map<String, String> headers) throws Exception {
        HttpResponse response = null;
        String responseJson = "";
        String jsluid = "", jslClearance = "", cookie = "";
        while (true) {
            response = HttpUtils.doGet(url, headers, null);
            responseJson = EntityUtils.toString(response.getEntity());
            if (response.getStatusLine().getStatusCode() == 200) {
                return responseJson;
            } else if (response.getStatusLine().getStatusCode() == 521) {
                Header[] headers1 = response.getHeaders("Set-Cookie");
                if (headers1 != null && headers1.length > 0) {
                    cookie = headers1[0].getValue();
                    jsluid = "__jsluid_s=" + cookie.split(";")[0].split("=")[1];
                    jslClearance = CrackJavaScript.getJslClearance(responseJson);
                    cookie = jsluid + ";" + jslClearance;
                    headers.put("Cookie", cookie);
                } else {
                    if (responseJson.contains("document.cookie")) {
                        jslClearance = CrackJavaScript.getJslClearance(responseJson);
                        cookie = jsluid + ";" + jslClearance;
                        headers.put("Cookie", cookie);
                    } else {
                        responseJson = responseJson.substring(responseJson.lastIndexOf("go(") + 3, responseJson.lastIndexOf(")"));
                        JSONObject data = JSONObject.parseObject(responseJson);
                        //<script>var _0x3c04=['wrMhGG0=','KMOnwoMR','Q3ROw7E=','w7zDjsKABQ==','wrgXPR4=','wq0SDsKT','cw/DgcKz','wpfDoEvCqA==','woQzwq46','w6PCqMKJw40=',
                        // 返回的数据需要进行解密
                        jslClearance = CookieUtils.go(data);
                        headers.put("Cookie", jsluid + ";" + jslClearance);
                    }
                }
            }
        }
    }

    /**
     * 设置请求头
     *
     * @return
     */
    public static Map<String, String> getHeader() {
        Map<String, String> headers = new HashMap<>();
        headers.put("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36");
        headers.put("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
        headers.put("Upgrade-Insecure-Requests", "1");
        headers.put("Cookie", "");
        return headers;
    }
}



